import config from "@/request/baseUrl.js";

// 转换服务器图片
export const webSrc = (src) => {
	return config.baseUrl + src;
};

// 去除HTML标签
export const delHtmlTag = (str) => {
	if (!str) return '';
	return str.replace(/(<([^>]+)>)/gi, "")
};

// 登录验证
export const author = (fn) => {
	if (uni.getStorageSync("TOKEN")) {
		fn();
	} else {
		uni.$emit("Authorize", Number(new Date()));
	}
};

// IM时间友好
export const timeToChat = (timestamp = null) => {
	if (timestamp == null) timestamp = Number(new Date());
	timestamp = parseInt(timestamp);
	// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
	if (timestamp.toString().length == 10) timestamp *= 1000;
	var timer = new Date().getTime() - timestamp;
	timer = parseInt(timer / 1000);
	// 如果小于5分钟,则返回"刚刚",其他以此类推
	let tips = "";
	switch (true) {
		case timer < 86400:
			tips = timeFormat(timestamp, "hh:MM");
			break;
		case timer >= 86400 && timer < 86400 * 7:
			var now = new Date(timestamp);
			var week = ["日", "一", "二", "三", "四", "五", "六"];
			switch (new Date().getDate() - now.getDate()) {
				case 1:
					tips = timeFormat(timestamp, "昨天 hh:MM");
					break;
				case 2:
					tips = timeFormat(timestamp, "前天 hh:MM");
					break;
				default:
					tips = "星期" + week[now.getDay()] + timeFormat(timestamp, "hh:MM");
			}
			break;
		case timer >= 86400 * 7:
			tips = timeFormat(timestamp, "mm-dd hh:MM");
			break;
		default:
			tips = timeFormat(timestamp, "yyyy-mm-dd hh:MM");
	}
	return tips;
};

/**
 * 社交时间友好
 */
export const timeToDate = (timestamp = null, format = "yyyy-mm-dd") => {
	if (timestamp == null) timestamp = Number(new Date());
	timestamp = parseInt(timestamp);
	// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
	if (timestamp.toString().length == 10) timestamp *= 1000;
	var timer = new Date().getTime() - timestamp;
	timer = parseInt(timer / 1000);
	// 如果小于5分钟,则返回"刚刚",其他以此类推
	let tips = "";
	switch (true) {
		case timer < 300:
			tips = "刚刚";
			break;
		case timer >= 300 && timer < 3600:
			tips = parseInt(timer / 60) + "分钟前";
			break;
		case timer >= 3600 && timer < 86400:
			tips = parseInt(timer / 3600) + "小时前";
			break;
		case timer >= 86400 && timer < 2592000:
			tips = parseInt(timer / 86400) + "天前";
			break;
		default:
			// 如果format为false，则无论什么时间戳，都显示xx之前
			if (format === false) {
				if (timer >= 2592000 && timer < 365 * 86400) {
					tips = parseInt(timer / (86400 * 30)) + "个月前";
				} else {
					tips = parseInt(timer / (86400 * 365)) + "年前";
				}
			} else {
				tips = timeFormat(timestamp, format);
			}
	}
	return tips;
};

// 时间格式化
export const timeFormat = (timestamp = null, fmt = "yyyy-mm-dd") => {
	// 其他更多是格式化有如下:
	// yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
	timestamp = parseInt(timestamp);
	// 如果为null,则格式化当前时间
	if (!timestamp) timestamp = Number(new Date());
	// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
	if (timestamp.toString().length == 10) timestamp *= 1000;
	let date = new Date(timestamp);
	let ret;
	let opt = {
		"y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"h+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"s+": date.getSeconds().toString(), // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(
				ret[1],
				ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
			);
		}
	}
	return fmt;
};

// 获取本地缓存
export const getStorage = (name) => {
	let data = uni.getStorageSync(name);
	return data ? JSON.parse(data) : "";
};

//  获取上级页面栈
export const prePage = (level = 2) => {
  let pages = getCurrentPages();
  let prePage = pages[pages.length - level];
  // #ifdef H5
  return prePage;
  // #endif
  // #ifndef H5
  return prePage.$vm;
  // #endif
};

// 赋值
export const pageckForIn = (ar1, ar2) => {
	Object.keys(ar1).forEach((key) => {
		ar1[key] = ar2[key];
	});
	return ar1;
};

// 计算时间差
export const getTimeDistance = (dateTime, limitDate) => {
  const targetDate = new Date(dateTime);
  const currentDate = limitDate ? new Date(limitDate) : new Date();
  
  const timeDifference = currentDate.getTime() - targetDate.getTime();

	const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
  const hours = Math.floor((timeDifference / (1000 * 60 * 60)) % 24);
  const minutes = Math.floor((timeDifference / (1000 * 60)) % 60);
	const seconds = Math.floor((timeDifference / 1000) % 60);
	let result = '';
  if (days > 0) result += `${days}天`;
	if (hours > 0) result += `${hours}小时`;
	if (minutes > 0) result += `${minutes}分钟`;
	if (days == 0 && hours == 0 && minutes == 0 && seconds > 0) result += `${seconds}秒`;
	return result;
}

// 获取日期范围
export const getDateRange = (type = "day") => {
	let date = new Date();
	let start = "";
	let end = "";
	if (type == "month") {
		// 本月
		let nextMonth = new Date(new Date().setMonth(date.getMonth() + 1));
		start = new Date(date.setDate(1)).toISOString().slice(0, 10);
		end = new Date(nextMonth.setDate(0)).toISOString().slice(0, 10);
	} else if (type == "lastmonth") {
		// 上月
		let lastDate = new Date();
		let year = lastDate.getFullYear();
		let month = date.getMonth();
		if (month == 0) {
			lastDate.setFullYear(year - 1);
			lastDate.setMonth(11);
			lastDate.setDate(1);
		} else {
			lastDate.setMonth(month - 1);
			lastDate.setDate(1);
		}
		start = new Date(lastDate).toISOString().slice(0, 10);
		end = new Date(date.setDate(0)).toISOString().slice(0, 10);
	} else if (type == "week") {
		// 本周
		let firstWeek = date.getDate() - date.getDay() + 1;
		let lastWeek = firstWeek + 6;
		let first = new Date(date.setDate(firstWeek));
		let last = new Date(date.setDate(lastWeek));
		start = first.toISOString().slice(0, 10);
		end = last.toISOString().slice(0, 10);
	} else if (type == "lastweek") {
		// 上周
		let firstWeek = date.getDate() - date.getDay() - 6;
		let lastWeek = firstWeek + 6;
		let first = new Date(date.setDate(firstWeek));
		let last = new Date(date.setDate(lastWeek));
		start = first.toISOString().slice(0, 10);
		end = last.toISOString().slice(0, 10);
	} else if (type == "day") {
		// 今天
		start = date.toISOString().slice(0, 10);
		end = date.toISOString().slice(0, 10);
	} else if (type == "lastday") {
		// 昨天
		date.setDate(date.getDate() - 1);
		start = date.toISOString().slice(0, 10);
		end = date.toISOString().slice(0, 10);
	}
	return [start, end];
};

// 枚举用户类型
export const enumUserType = (val) => {
	switch (val) {
		case "00":
			return "系统用户";
		case "01":
			return "消防技术服务机构";
		case "02":
			return "委托单位";
		case "03":
			return "一级注册消防工程师";
		case "04":
			return "消防设施操作员 ";
		case "05":
			return "平台维修员";
		default:
			return "--";
	}
};

// 比较版本大小
export function compareVersion(v1, v2) {
	v1 = v1.split(".");
	v2 = v2.split(".");
	const len = Math.max(v1.length, v2.length);
	while (v1.length < len) {
		v1.push("0");
	}
	while (v2.length < len) {
		v2.push("0");
	}
	for (let i = 0; i < len; i++) {
		const num1 = parseInt(v1[i]);
		const num2 = parseInt(v2[i]);
		if (num1 > num2) {
			return 1; // v1大
		} else if (num1 < num2) {
			return -1; // v2大
		}
	}
	return 0; // 一样大
}